import sys
from PyQt5.QtWidgets import QApplication, QPushButton, QWidget, \
QVBoxLayout,QHBoxLayout,QLineEdit,QLabel
from PyQt5.QtCore import QSize # 导入 QSize
import rclpy
from rclpy.node import Node
from std_msgs.msg import String,Bool
from mower_msgs.srv import MapNameSrv

# 定义 ROS 2 节点类
class PyQtROSNode(Node):
    def __init__(self):
        super().__init__('panel_node')
        self.publisher_ = self.create_publisher(Bool, 'cutterhead_ctl', 1)

        # 调用服务
        self.__map_save_client = self.create_client(MapNameSrv, '/map_save')

    
    def publish_message(self, msg: bool):
        msg_to_publish = Bool()
        msg_to_publish.data = msg
        self.publisher_.publish(msg_to_publish)
        self.get_logger().info(f'Publishing: "{msg_to_publish.data}"')

    def map_save(self,msg: str):
        while not self.__map_save_client.wait_for_service(timeout_sec=1.0):
            print("error")
            return

        req = MapNameSrv.Request()
        req.map_name = msg
        self.__map_save_client.call(req)



#-------------------------------------#

# 定义开关按钮类
class ToggleSwitch(QPushButton):
    def __init__(self,label):
        super().__init__(label)
        self.setCheckable(True) # 设置为可切换状态
        self.setFixedSize(QSize(100, 40))   # 设置按钮大小
        self.setStyleSheet(self.get_style()) # 设置样式
        self.clicked.connect(self.toggle_style) # 点击事件

    def toggle_style(self):
        # 根据按钮的状态切换样式
        self.setStyleSheet(self.get_style())

    def get_style(self):
        # 样式表定义开关按钮样式
        # 如果按钮被按下，显示开启状态为绿色，否则为关闭状态灰色

        if self.isChecked():
            return f"""
                QPushButton {{
                    background-color: #4CAF50;
                    color: white;
                    font-size: 16px;
                    border: none;
                    border-radius: 5px;
                    padding: 5px;
                }}
            """
        else:
            return f"""
                QPushButton {{
                    background-color: #ccc;
                    color: black;
                    font-size: 16px;
                    border: none;
                    border-radius: 5px;
                    padding: 5px;
                }}
            """



# 定义 PyQt5 窗口类
class MainWindow(QWidget):
    def __init__(self, ros_node):
        super().__init__()
        self.ros_node = ros_node
        self.init_ui()

    def init_ui(self):
        self.setWindowTitle('mower control panel')
        self.resize(986, 858)
        
        # 创建标签、输入框、按钮
        label = QLabel('地图名', self)
        self.line_edit = QLineEdit(self)
        save_button = QPushButton('保存', self)
        save_button.clicked.connect(self.on_button_click_map_save)

        # 水平布局
        h_layout = QHBoxLayout()
        h_layout.addWidget(label)
        h_layout.addWidget(self.line_edit)
        h_layout.addWidget(save_button)

 
        # 创建按钮并设置按钮文字为 "刀盘电机"
        self.switch = ToggleSwitch("刀盘电机")
       
        self.switch.clicked.connect(self.on_button_click)


        # 布局
        main_layout  = QVBoxLayout()
        button_layout = QHBoxLayout()  # 水平布局用于按钮放置

        # 按钮放置在水平布局中并居中
        button_layout.addStretch()  # 添加弹性空间
        button_layout.addWidget(self.switch)
        button_layout.addStretch()  # 添加弹性空间

        # 主垂直布局
        # 将水平布局添加到主布局中
        main_layout.addStretch()  # 添加弹性空间，使按钮在垂直方向居中
        main_layout.addLayout(h_layout)  # 将地图名输入和保存按钮添加
        main_layout.addLayout(button_layout)  # 将开关按钮添加
        main_layout.addStretch()  # 添加弹性空间，使按钮在垂直方向居中

     
        self.setLayout(main_layout)

    def on_button_click(self):
        # 按钮点击事件，发布 ROS 2 消息
        if self.switch.isChecked():
            # 刀盘电机开启
            self.ros_node.publish_message(True) 
        else:
            # 刀盘电机关闭
            self.ros_node.publish_message(False) 
    
    def on_button_click_map_save(self):
        '''
        '''
        map_name = self.line_edit.displayText()
        print(map_name)
        self.ros_node.map_save(map_name)




        

    def closeEvent(self, event):
        # 在关闭窗口时，关闭 ROS 2 节点
        self.ros_node.destroy_node()
        rclpy.shutdown()
        event.accept()




def main():
    # 初始化 ROS 2
    rclpy.init()

    # 创建 ROS 2 节点
    ros_node = PyQtROSNode()

    # 初始化 PyQt 应用程序
    app = QApplication(sys.argv)
    window = MainWindow(ros_node)
    window.show()

    # 启动 PyQt5 应用程序
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()